package Function.Utils;

import java.io.*;

/**
 * 说明：
 */
public class CacheFileUtil {

    private static volatile CacheFileUtil util;

    public static CacheFileUtil getInstance() {
        if (util == null) {
            synchronized (CacheFileUtil.class) {
                if (util == null) {
                    util = new CacheFileUtil();
                }
            }
        }
        return util;
    }

    private CacheFileUtil() {

    }


    public void saveCacheInfo(String filePath, String info) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file, false);
            byte[] bytes = info.getBytes();
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] ^= 'B';
            }
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (
                FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String readCacheInfo(String filePath) {
        StringBuilder stringBuffer = new StringBuilder();

        // 打开文件输入流
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return null;
            }
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[512];
            int len = fileInputStream.read(buffer);
            // 读取文件内容
            while (len > 0) {
                for (int i = 0; i < len; i++) {
                    buffer[i] ^= 'B';
                }
                stringBuffer.append(new String(buffer, 0, len));
                // 继续将数据放到buffer中
                len = fileInputStream.read(buffer);
            }
            // 关闭输入流
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return stringBuffer.toString();
    }


}
